﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using System.Web.Security;

namespace TireService.Web.Casehandling
{
    public partial class TireSetLogList : System.Web.UI.Page
    {

        public int TireSetId
        {
            get
            {
                if (ViewState["_tiresetid"] != null)
                    return (int)ViewState["_tiresetid"];
                else
                    return 0;
            }
            set
            {
                ViewState["_tiresetid"] = value;
            }
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            // Register export button as full postback - otherwise it wount work because it is inside a update panel
            ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
            scriptManager.RegisterPostBackControl(this.btnExport.FindControl("btnExport"));
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            // Mulighed for goback (Javascript:Goback(-1))
            // TODO: Vis liste over log historik
            // TODO: Vis grunddata på dæk
            // TODO: Mulighed for
            // 1. Lav dækskifte (byt rundt på to dæk - KUN aktive dæk, ikke INAktive. Oplys dækmønstre)
            // 2. Kasser dæk (Sættes som inaktive - lav note)
            // 3. Dækflyt - flyt dæk til anden lager lokation
        
            TireServiceDB db = new TireServiceDB();

            if (Page.IsPostBack != true)
            {
                // Get customer id
                try
                {
                    // Get customer Id and save to propertie
                    if (Request.QueryString["TireSetId"] != null)
                    {
                        this.TireSetId = Convert.ToInt32(Request.QueryString["TireSetId"]);
                    }
                    else
                    {
                        Response.Redirect("~/Casehandling/CustomerList.aspx");
                    }
                }
                catch (Exception)
                {
                    // Nothing - invalid customerid, not an integer - send user back to previous page
                    Response.Redirect("~/Casehandling/CustomerList.aspx");
                }
            }


            // Bind tireset data to form
            BindTireSetData(db, this.TireSetId);

            // Bind tireset log data to gridview
            BindTireSetLogData(db, this.TireSetId);

            // Change gridview pagesize based on dropdownlist
            gvTireSetLog.SettingsPager.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);

            // Dispose connection to database
            db.Dispose();
        }

        private void BindTireSetData(TireServiceDB db, int TireSetId)
        {
            TireSet tireset = db.GetTireSet(TireSetId);

            if (tireset != null)
            {
                // Show tireset data in UI
                lblTireType.Text = db.GetTireTypeDescription(tireset.TireTypeId);
                lblDimensions.Text = tireset.Width.ToString() + " / " + tireset.Height.ToString() + " " + tireset.Size.ToString();
                if (tireset.TireSpeedIndexId != null)
                {
                    lblTireSpeedIndex.Text = db.GetTireSpeedIndexDescription(Convert.ToInt32(tireset.TireSpeedIndexId));
                }
                else
                {
                    lblTireSpeedIndex.Text = "";
                }
                if (tireset.TireBrandId != null)
                {
                    lblTireBrand.Text = db.GetTireBrandDescription(Convert.ToInt32(tireset.TireBrandId));
                }
                else
                {
                    lblTireBrand.Text = "";
                }
                lblTireBrandNote.Text = tireset.TireBrandNote;
                cbHubCaps.Checked = tireset.HubCaps;
                cbLockingBolt.Checked = tireset.LockingBolt;
                cbRimProtection.Checked = tireset.RimProtection;
                cbRunFlatTire.Checked = tireset.RunFlatTire;
                lblTireSetStatus.Text = db.GetTireSetStatusDescription(tireset.TireSetStatusId);
                if (tireset.ContainerCargoRoomId != null)
                {
                    ContainerCargoRoom cargoroom = db.GetContainerCargoRoom(Convert.ToInt32(tireset.ContainerCargoRoomId));

                    if (cargoroom != null)
                    {
                        lbtnContainerCargoRoomId.Text = tireset.ContainerCargoRoomId.ToString();
                        lbtnContainerCargoRoomId.PostBackUrl = "~/Casehandling/EditContainer.aspx?ContainerId=" + cargoroom.ContainerId.ToString();       
                    }
                }
                if (tireset.TireLoadIndexId != null)
                {
                    lblTireLoadIndex.Text = db.GetTireLoadIndexDescription(Convert.ToInt32(tireset.TireLoadIndexId));
                }
                else
                {
                    lblTireLoadIndex.Text = "";
                }
                if (tireset.ManufactureDate != null)
                {
                    lblManufactureDate.Text = Convert.ToDateTime(tireset.ManufactureDate).ToShortDateString();    
                }
                lblSocketWrenchSize.Text = tireset.SocketWrenchSize.ToString();
            }
            else
            {
                // Tireset not found - redirect to customer page
                Response.Redirect("~/Casehandling/CustomerList.aspx");
            }
        }

        /// <summary>
        /// Function that bind customer data to gridview
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="TireSetId">Id on tireset</param>
        private void BindTireSetLogData(TireServiceDB db, int TireSetId)
        {
            gvTireSetLog.DataSource = db.GetTireSetLog(TireSetId);
            gvTireSetLog.DataBind();
        }

        #region Private Functions

        /// <summary>
        /// Function that runs specific action
        /// </summary>
        /// <param name="Action">Id for action to run</param>
        protected void SubmitAction(int Action)
        {
            if (Action == 0)
            {
                throw new ArgumentException("Ingen handling valgt.");
            }
        }

        #endregion

        #region Control Functions

        /// <summary>
        /// Button function for export of gridview
        /// </summary>
        protected void btnExport_Click(object sender, EventArgs e)
        {
            if (ddlExport.SelectedValue == "0")
            {
                gvExport.WritePdfToResponse();
            }

            if (ddlExport.SelectedValue == "1")
            {
                gvExport.WriteXlsToResponse();
            }

            if (ddlExport.SelectedValue == "2")
            {
                gvExport.WriteCsvToResponse();
            }

            if (ddlExport.SelectedValue == "3")
            {
                gvExport.WriteRtfToResponse();
            }
        }

        /// <summary>
        /// Button function that submit selected action in action dropdownlist
        /// </summary>
        protected void btnSubmitAction_Click(object sender, EventArgs e)
        {
            try
            {
                SubmitAction(Convert.ToInt32(ddlAction.SelectedValue));
            }
            catch (Exception ex)
            {
                if ((ex) is ArgumentException)
                {
                    // User error - arguments not valid - show error message
                    lMessage.Text = ((ArgumentException)ex).Message;
                }
                else
                {
                    // System error - show general error message
                    lMessage.Text = "Fejl opstod - venligst prøv igen";
                }
            }
            finally
            {
                // Update message panel
                upMessage.Update();
            }
        }

        #endregion


        #region GridView Functions

        /// <summary>
        /// Gridview function that handles customer buttons in gridview
        /// </summary>
        protected void gvTireSetLog_CustomButtonCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomButtonCallbackEventArgs e)
        {
            //if (e.ButtonID == "Edit")
            //{
            //    try
            //    {
            //        // Get contactid
            //        object cellCustomerId = gvCustomer.GetRowValues(e.VisibleIndex, "CustomerId");

            //        // Go to edit mode
            //        Session["CustomerId"] = Convert.ToInt32(cellCustomerId);
            //        Response.Redirect("~/Casehandling/EditCustomer.aspx");
            //    }
            //    catch (Exception ex)
            //    {
            //        if ((ex) is ArgumentException)
            //        {
            //            // User error - arguments not valid - show error message
            //            lMessage.Text = ((ArgumentException)ex).Message;
            //        }
            //        else
            //        {
            //            // System error - show general error message
            //            lMessage.Text = "Fejl opstod - venligst prøv igen";
            //        }
            //    }
            //    finally
            //    {
            //        // Update message panel
            //        upMessage.Update();
            //    }
            //}
        }

        /// <summary>
        /// Gridview function that change field data for unbound fields
        /// </summary>
        protected void gvTireSetLog_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
        {
            // Format UnBoundColumn FromTireSetStatusDescription: Show from status description
            if (e.Column.FieldName == "FromTireSetStatusDescription")
            {
                // Get fromstatusid
                int fromstatusid = Convert.ToInt32(e.GetListSourceFieldValue("FromTireSetStatusId"));

                TireServiceDB db = new TireServiceDB();

                // Change field value
                // Change field value
                if (fromstatusid != 0)
                {
                    e.Value = db.GetTireSetStatusDescription(fromstatusid);
                }
                else
                {
                    e.Value = "";
                }
                
                db.Dispose();
            }

            // Format UnBoundColumn ToTireSetStatusDescription: Show to status description
            if (e.Column.FieldName == "ToTireSetStatusDescription")
            {
                // Get tostatusid
                int tostatusid = Convert.ToInt32(e.GetListSourceFieldValue("ToTireSetStatusId"));

                TireServiceDB db = new TireServiceDB();

                // Change field value
                e.Value = db.GetTireSetStatusDescription(tostatusid);

                db.Dispose();
            }

            // Format UnBoundColumn UserName: Show username
            if (e.Column.FieldName == "UserName")
            {
                // Get userid
                string userid = Convert.ToString(e.GetListSourceFieldValue("UserId"));

                // Change field value
                e.Value = Membership.GetUser(new Guid(userid));
            }
        }

        #endregion

    }
}